var pagecontext_ctx = $("#pagecontext_ctx").val();
var passwordReg = /[0-9 | A-Z | a-z]{6}/;

//查看所有的角色
function search_roles(){
}

$(function(){
	
	
	$( "#search_office" ).autocomplete({
		source: function( request, response ) {
		jQuery.support.cors = true;
		$.ajax({
			url: pagecontext_ctx + "/basic/getChooseOfficeCode",
			dataType: "json",
			data:{
			code: request.term
			},
			beforeSend: function (xhr) {
			
		    },
		success: function( data ) {
			response( $.map(data.offices, function( item ) {
			return {
				label:item.label,
                uniq_code:item.uniq_code
			}
			}));
		}
		});
		},
		minLength: 1,
		select: function( event, ui ) {
			var item = ui.item;
			//$("#search_office").val(item.uniq_code);
		}
		});
	
	$( "#save_office" ).autocomplete({
		source: function( request, response ) {
		jQuery.support.cors = true;
		$.ajax({
			url: pagecontext_ctx + "/basic/getChooseOfficeCode",
			dataType: "json",
			data:{
			code: request.term
			},
			beforeSend: function (xhr) {
			
		    },
		success: function( data ) {
			response( $.map(data.offices, function( item ) {
			return {
				label:item.label,
                uniq_code:item.uniq_code
			}
			}));
		}
		});
		},
		minLength: 1,
		select: function( event, ui ) {
			var item = ui.item;
			//$("#search_office").val(item.uniq_code);
		}
		});
	
	$( "#update_office" ).autocomplete({
		source: function( request, response ) {
		jQuery.support.cors = true;
		$.ajax({
			url: pagecontext_ctx + "/basic/getChooseOfficeCode",
			dataType: "json",
			data:{
			code: request.term
			},
			beforeSend: function (xhr) {
			
		    },
		success: function( data ) {
			response( $.map(data.offices, function( item ) {
			return {
				label:item.label,
                uniq_code:item.uniq_code
			}
			}));
		}
		});
		},
		minLength: 1,
		select: function( event, ui ) {
			var item = ui.item;
			//$("#search_office").val(item.uniq_code);
		}
		});
	
	
	
	//左侧导航
	setMenu(pagecontext_ctx+"/user_manage/user_manage");
	
	//刚进入页面
	 rolepage(null);
	 
	 function rolepage(page){
		 //console.log(rolename)
		//ajax发送之前显示loading
		 $("#loading").show();
		 //登录名称
		 var search_name = $("#search_name").val();
		 //用户名称
		 var search_userName = $("#search_userName").val();
		 //所属科室
		 var search_office = $("#search_office").val();
		 
		 $.ajax({
			 type:"post",
			 url:pagecontext_ctx+"/userHospital/findUserHospitalListPage",
			 data:{"page":page, "loginName":search_name, "name":search_userName, "officeCode":search_office},
			 dataType:"json", 
			 success:function(result){
				// Ajax请求结束的时候触发
		            setTimeout(function(){
		                 $('#loading').hide();
		                },500);
	               if(result.page.list.length==0){
	            	   $("#tableList").html("");
	                      $("#pageUI").html("");
	                	   layer.msg("暂无数据！");
	                	   return false;
	               }
	              
	              var content="";
	              $.each(result.page.list,function(i, item){
	            	  var id = "";
			 			if(item.id != "" && item.id != null) {
			 				guid = item.id;
			 			}
			 			
			 			content+="<tr class='parent' data-guid='"+guid+"'>";
			 			//用户名称
			 			var loginName = "";
			 			if(item.loginName!=null && item.loginName!='') {
			 				loginName=item.loginName;
			 			}
			 			content+="<td>"+loginName+"</td>";
			 			//所属角色
			 			//var roles = "";
			 			//content+="<td><a href='javascript:void(0)' class='a_hover' onclick='search_roles()'>查看角色</a></td>";
			 			
			 			
			 			//用户名称
			 			var name = "";
			 			if(item.name != null && item.name != '') {
			 				name = item.name;
			 			}
			 			content+="<td>"+name+"</td>";
			 			
			 			//所属科室
			 			var officeName = "";
			 			if(item.officeName != null && item.officeName != '') {
			 				officeName = item.officeName;
			 			}
			 			content+="<td>"+officeName+"</td>";
			 			
			 			var loginDate = "";
			 			if(item.loginDate!='' && item.loginDate != null) {
			 				loginDate = item.loginDate;
			 			}
			 			//最后登录时间
			 			content+="<td>"+loginDate+"</td>";
			 			
			 			if(item.isAcvicate == 1) {
			 				content+="<td><button class='btn btn-xs btn-info isActivate_class' data="+item.id+" isActivate='2'><i class='ace-icon fa fa-pencil bigger-120'></i>禁用</button>&nbsp;";
			 			}else {
			 				content+="<td><button class='btn btn-xs btn-info isActivate_class' data="+item.id+" isActivate='1'><i class='ace-icon fa fa-pencil bigger-120'></i>启用</button>&nbsp;";
			 			}
			 			
			 			content+="<button class='btn btn-xs btn-info updatePassword_class' data="+item.id+"><i class='ace-icon fa fa-pencil bigger-120' ></i>修改密码</button>&nbsp;";
			 			content+="<button class='btn btn-xs btn-warning allot_role_class'  data="+item.id+"><i class='ace-icon fa fa-key bigger-120 addRole'></i>分配角色</button>&nbsp;";
			 			content+="<button class='btn btn-xs btn-warning updateUserName'  data="+item.id+" dataName="+item.name+" dataOfficeName="+item.officeName+"><i class='ace-icon fa fa-key bigger-120'></i>修改用户信息</button></td>";
			 			content+="</tr>";
	              });
	              //将内容渲染在body中
	              $("#tableList").html(content);
	              
		 			var element = $("#pageUI");	
					var options = {
									 bootstrapMajorVersion:3,
									 currentPage:result.page.currentPage,
									 numberOfPages:3,
									 totalPages:result.page.totalPage,
								     itemTexts: function(type, page, current) { //修改显示文字
						                switch (type) {
						                case "first":
						                    return "第一页";
						                case "prev":
						                    return "上一页";
						                case "next":
						                    return "下一页";
						                case "last":
						                    return "最后一页";
						                case "page":
						                    return page;
						                }
								     },
									 onPageChanged:function(event, originalEvent, currentPage){
										rolepage(currentPage);
									 }
					               }; //----options
		           element.bootstrapPaginator(options);
		           
		           //a标签加下划线
		           $(".a_hover").on("mousemove", function() {
		        	   $(this).css("text-decoration", "underline");
		           });
		           
		           $(".a_hover").on("mouseout", function() {
		        	   $(this).css("text-decoration", "none");
		           });
		           
		           //修改密码
		      	 $(".updatePassword_class").on("click", function() {
		      		 $("#update_old_password").val("");
		    		 $("#update_new_password").val("");
		    		 $("#update_repeat_new_password").val("");
		    		 $("#update_password_guid").val("");
		    		 $("#update_password_guid").val($(this).attr("data"));
		      		 $("#update_password_modal").modal("show");
		      	 });
		      	 
		      	 //禁用或者启用
		      	 $(".isActivate_class").on("click", function() {
		      		  var id = $(this).attr("data");
		      		  var isActivate = $(this).attr("isActivate");
		      		  var message = "";
		      		  if(isActivate == 1) {
		      			message = '你确定启用这个账号吗？';
		      		  }else {
		      			message = '你确定禁用这个账号吗？';
		      		  }
		      		  
		      		layer.msg(message, {
                        time: 0 //不自动关闭
                        ,btn: ['确定', '取消']
                        ,yes: function(index){
                            //点击确定后发送删除请求
                               layer.close(index);
                                   //console.log(dataGuid)
                                 $.ajax({
                                        type:"post",
                                        url:pagecontext_ctx+"/userHospital/updateUserHospitalByIsAcvicateAndId",
                                        data:{"id":id, "isActivate":isActivate},
                                        dataType:"json",
                                        success:function(result){
                                               if(result.success){
                                                     layer.msg(result.msg);
                                                     location= pagecontext_ctx+"/user_manage/user_manage";
                                              }else{
                                                     layer.msg(result.msg);
                                              }
                                        }, error:function(XMLHttpRequest, textStatus, errorThrown) {
                          if(XMLHttpRequest.status == 403) {
                              alert("没有权限!");
                       }
                   }  //error end
                                 }); //-------ajax end-------
                           }
                      });
		      	 });
		      	 
		      	 $("#sava_user_hospital_modal").on("click", function() {
		      		 $("#sava_reset").trigger("click");
		      		 $("#Add").modal("show");
		      	 });
		      	 
		      	 
		      	 //创建账号
		      	 $("#sava_user_hospital").on("click", function() {
		      		 var loginName = $("#sava_loginName").val();
		      		 var password = $("#sava_password").val();
		      		 var secondPassword = $("#sava_second_passowrd").val();
		      		 var isActivate = $("input[name='save_activate']:checked").val();
		      		 //var officeCode = $("#save_office").find("option:selected").val();
		      		 var officeName = $("#save_office").val();
		      		 
		      		 //用户名
		      		 var userName = $("#sava_userName").val();
		      		 
		      		 if(loginName == null || loginName == '') {
		      			 layer.msg("登录名称不能为空!");
		      			 return;
		      		 }
		      		 
		      		 if(officeName == null || officeName == '') {
		      			 layer.msg("请选择所属科室!");
		      			 return;
		      		 }
		      		 
		      		 if(userName == null || userName == '') {
		      			 layer.msg("用户名称不能为空!");
		      			 return;
		      		 }
		      		 
		      		 if(password == null || password == '') {
		      			 layer.msg("密码不能为空!");
		      			 return;
		      		 }
		      		 
		      		 var re = new RegExp(passwordReg);
		      		 if(!re.test(password)) {
		      			 layer.msg("密码至少为6位以上的数字或字母!");
		      			 return ;
		      			 
		      		 }
		      		 
		      		if(secondPassword == null || secondPassword == '') {
		      			 layer.msg("重新输入密码不能为空!");
		      			 return;
		      		 }
		      		
		      		if(!re.test(secondPassword)) {
		      			layer.msg("密码至少为6位以上的数字或字母!");
		      			return;
		      		}
		      		
		      		if(password != secondPassword) {
		      			layer.msg("两次输入密码不一样!");
		      		}
		      		var dataJson = {"loginName":loginName, "password":password, "isAcvicate":isActivate, "name":userName, "officeName":officeName};
		      		
		            $.ajax({
                      type:"post",
                      url:pagecontext_ctx+"/userHospital/saveUserHospitals",
                      data:dataJson,
                      dataType:"json",
                      success:function(result){
                             if(result.success){
                                   layer.msg(result.msg);
                                   location = pagecontext_ctx+"/user_manage/user_manage";
                            }else{
                                   layer.msg(result.msg);
                            }
                      }, error:function(XMLHttpRequest, textStatus, errorThrown) {
        if(XMLHttpRequest.status == 403) {
            alert("没有权限!");
     }
 }  //error end
              }); //-------ajax end-------
		      	 });
		      	 
		      	 //修改用户名
		      	 $(".updateUserName").on("click", function() {
		      		 var id = $(this).attr("data");
		      		 var name = $(this).attr("dataName");
		      		 var officeName = $(this).attr("dataOfficeName");
		      		
		      		 $("#user_id").val("");
		      		 $("#user_name").val("");
		      		 $("#update_office").val("");
		      		 
		      		 $("#user_id").val(id);
		      		 
		      		 if (name != null && name != "null") {
		      			 $("#user_name").val(name);
		      		 } else {
		      			 $("#user_name").val("");
		      		 }
		      		 
		      		 $("#update_office").val(officeName);
		      		 
		      		 /*if(officeCode != null && officeCode != '') {
		      			$("#update_office").find("option").each(function() {
		      				if ($(this).val() == officeCode) {
		      					$(this).prop("selected", true);
		      				}
		      			});
		      		 }*/
		      		 
		      		 
		      		 $("#updateUserName_modal").modal("show");
		      	 });
		      	 
		      	 //分配角色
		      	 $(".allot_role_class").on("click", function() {
		      		 var id = $(this).attr("data");
		      		 //查询所有的角色
		    		 $.get(pagecontext_ctx+"/role/findRolesListByUserHospitalId", {"id":id}, function(result) {
		    			 if(result.roleList == null) {
		    				 layer.msg("请先创建角色!");
		    				 return;
		    			 }
		    			 
		    			 var content = "";
		    			 $.each(result.roleList, function(index, role) {
		    				content+="<div class='checkbox'>";
		    				content+="<label>";
		    				if(role.role_user_id != null && role.role_user_id != '') {
		    					content+="<input type='checkbox' class='sava_allot_role' checked data="+role.id+" userId="+id+">"+role.role_name;
		    				} else {
		    					content+="<input type='checkbox' class='sava_allot_role' data="+role.id+" userId="+id+">"+role.role_name;
		    				}
		    				content+=""; 
		    				content+="</label>"; 
		    				content+="</div>"; 
		    			 });
		    			 $("#allot_role").html("");
			    		 $("#allot_role").append(content);
			    		 
		    		 }, 'json');
		      		 
		      		 $("#allot_role_modal").modal("show");
		      		 
		      	 });
		      	 
			   } , error:function(XMLHttpRequest, textStatus, errorThrown) {
                   $("#loading").hide();
				   if(XMLHttpRequest.status == 403) {
                       alert("没有权限!");
                }
          }  //error end 

			 })
	 } //分页结束
	 
	//分页查询
	 $("#user_manager_Search").on("click", function(){
		 rolepage(null);
	 });
	 
	 //分配角色
	 $("#a_allot_role").on("click", function() {
		 var userId = "";
		 var roleStr = "";
		 var roleArray = [];
		 $(".sava_allot_role").each(function() {
			 var roleId = $(this).attr("data");
			 userId = $(this).attr("userId");
			 if($(this).is(":checked")) {
				 roleArray.push(roleId);
			 }
		 });
		 roleStr = roleArray.join(",");
		 var url = pagecontext_ctx+"/userRole/updateUserRoleByUserId";
		 $.ajax({
             type: "post",
             url: url,
             dataType:"json",
             data:{"roleStr":roleStr, "userId":userId},
             success: function (result) {
            	 if(result.success) {
    				 layer.msg(result.msg);
    				 location = pagecontext_ctx+"/user_manage/user_manage";
    				 $("#allot_role_modal").modal("hide");
    			 } else {
    				 layer.msg(result.msg);
    			 }
             },error:function(XMLHttpRequest, textStatus, errorThrown) {
                 if(XMLHttpRequest.status == 403) {
                     alert("没有权限!");
              }
        }  //error end 
         }); //------ajax end-------

		 
		 
	 });
	 
	 //修改用户信息
	 $("#update_userName_form").on("click", function() {
		 var userId = $("#user_id").val();
		 var userName = $("#user_name").val();
		 
		 if (userName == null || userName == "") {
			 layer.msg("用户名称不能为空!");
			 return;
		 }
		 
		/* var officeCode = $("#update_office").val();*/
		 var officeName = $("#update_office").val();
		 
		 if (officeName == null || officeName == '') {
			 layer.msg("请选择所属科室!");
			 return;
		 }
		 console.log("所属科室------" + officeName);
		 
		 $.ajax({
	            type: "post",
	            url: pagecontext_ctx+"/userHospital/updateUserName",
	            dataType:"json",
	            data: {"id":userId, "userName":userName, "officeName":officeName},
	            success: function (result) {
	            	if(result.success) {
	      				layer.msg(result.msg);
	      				$("#updateUserName_modal").modal("hide");
	      				//重新刷新用户列表
	      				location = pagecontext_ctx+"/user_manage/user_manage";
	      			} else {
	      				layer.msg(result.msg);
	      			}
	            }, error:function(XMLHttpRequest, textStatus, errorThrown) {
	                if(XMLHttpRequest.status == 403) {
	                    layer.msg("没有权限!");
	             }
	       }  //error end 
	        }); //--------ajax end----------
	 });
	 
	 
	 //修改密码
	 $("#a_update_password").on("click", function(){
		var re = new RegExp(passwordReg);
  		
		var update_new_password = $("#update_new_password").val();
  		var update_repeat_new_password = $("#update_repeat_new_password").val();
  		
  		if(update_new_password == null || update_new_password == '') {
  			layer.msg("新密码不能为空!");
  			return;
  		}
  		
  		 if(!re.test(update_new_password)) {
  			 layer.msg("新密码至少为6位以上的数字或字母!");
  			 return ;
  		 }
  		
  		
  		if(update_repeat_new_password == null || update_repeat_new_password == '') {
  			layer.msg("重复新密码不能为空!");
  			return;
  		}
  		
  		 if(!re.test(update_repeat_new_password)) {
  			 layer.msg("重复新密码至少为6位以上的数字或字母!");
  			 return ;
  		 }
  		
  		if(update_new_password != update_repeat_new_password) {
  			layer.msg("两次输入密码不一致!");
  			return;
  		}
  		
  		var id = $("#update_password_guid").val();
  		
  		$.ajax({
            type: "post",
            url: pagecontext_ctx+"/userHospital/updatePasswordById",
            dataType:"json",
            data: {"id":id, "password":update_new_password},
            success: function (result) {
            	if(result.success) {
      				layer.msg(result.msg);
      				$("#update_password_modal").modal("hide");
      				location = pagecontext_ctx+"/user_manage/user_manage";
      			} else {
      				layer.msg(result.msg);
      			}
            }, error:function(XMLHttpRequest, textStatus, errorThrown) {
                if(XMLHttpRequest.status == 403) {
                    layer.msg("没有权限!");
             }
       }  //error end 
        }); //--------ajax end----------
  		
	 });
	 
	 //创建账号
	 $("#a_create_account").on("click", function(){
		 var guid = $("#create_account_guid").val();
		 
  		var loginName = $("#account_loginName").val();
  		var password = $("#account_password").val();
  		var confirmPassword = $("#confirm_password").val();
  		
  		if(loginName == null || loginName == '') {
  			alert("账号不能为空!");
  			return;
  		}
  		
  		if(password == null || password == '') {
  			alert("密码不能为空!");
  			return;
  		}
  		
  		if(confirmPassword != password) {
  			alert("确认密码输入错误!");
  			return;
  		}
  		
  		$.ajax({
            type: "post",
            url: pagecontext_ctx+"/user/create/account",
            dataType:"json",
            data: {"guid":guid, "password":password, "loginName":loginName},
            success: function (result) {
            	if(result.success) {
      				alert(result.msg);
      				location=pagecontext_ctx+"/user_manage/user_manage";
      				$("#create_account_modal").modal("hide");
      			} else {
      				alert(result.msg);
      			}
            }, error:function(XMLHttpRequest, textStatus, errorThrown) {
                if(XMLHttpRequest.status == 403) {
                    alert("没有权限!");
             }
       }  //error end 
        }); //--------ajax end----------

  		
	 });
   
})